﻿using System.Linq;
using JetBrains.Annotations;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Localization.Models;
using So.BackendAdditions.Models;

namespace So.BackendAdditions.Drivers
{
    [UsedImplicitly]
    public class LocalizationPartDriver : ContentPartDriver<LocalizationPart>
    {
        private readonly IContentManager _contentManager;

        public LocalizationPartDriver(IContentManager contentManager)
        {
            _contentManager = contentManager;
        }

        protected override DriverResult Display(LocalizationPart part, string displayType, dynamic shapeHelper)
        {
            if (part.MasterContentItem == null || part.MasterContentItem.Id == 0)
            {
                return Combined(
                    ContentShape("Parts_BackendAdditions_LocalizedContentList_SummaryAdmin",() => shapeHelper.Parts_BackendAdditions_LocalizedContentList_SummaryAdmin(
                        ItemCulture: part.Culture.Culture,
                        MasterId : part.Id,
                        LocalizedChildren: _contentManager.Query(VersionOptions.Latest)
                            .Where<LocalizationPartRecord>(s => s.MasterContentItemId == part.Id).List()
                            .Select(s => new LocalizedItemSummaryAdminViewModel
                            {
                                Name = s.As<LocalizationPart>().Culture.Culture,
                                Shape = _contentManager.BuildDisplay(s, "SummaryAdmin")
                            }).ToList()
                    ))
                );
            }
            return null;
        }
    }
}